# -*- cod1ng:UTF-8 -*- #
"""
@filename:AI_多对话.py
@author:Qian
@time:2025-01-05
"""
from openai import OpenAI

client = OpenAI(
    api_key="sk-oRwfsGJ7rT8fyPER24qT6C3XY8NamrhTPCUl7Xnn8dJumybh",
    base_url="https://api.chatanywhere.tech/v1"
)


def gpt_35_api(messages: list):
    """为提供的对话消息创建新的回答"""
    completion = client.chat.completions.create(model="gpt-3.5-turbo", messages=messages)
    return completion.choices[0].message.content

def gpt_35_api_stream(messages: list):
    """为提供的对话消息创建新的回答 (流式传输)"""
    stream = client.chat.completions.create(
        model='gpt-3.5-turbo',
        messages=messages,
        stream=True,
    )
    response = ""
    for chunk in stream:
        if chunk.choices[0].delta.content is not None:
            response += chunk.choices[0].delta.content
            print(chunk.choices[0].delta.content, end="")
    return response

if __name__ == '__main__':
    messages = [{'role': 'user', 'content': '你好'}]

    while True:
        # 获取模型的回复
        response = gpt_35_api(messages)
        print("\nAI:", response)

        # 将 AI 的回复添加到消息历史中
        messages.append({'role': 'assistant', 'content': response})

        # 获取用户输入
        user_input = input("你: ")
        messages.append({'role': 'user', 'content': user_input})